﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
using System.Xml.Linq;

namespace Revisions
{
    public class RevisionRunner
    {
        public static int RunRevisions(SqlConnection conn)
        {

            XDocument revDoc = XDocument.Load("RevisionList.xml");

            int count = 0;

            foreach (XElement node in revDoc.Descendants("Revision"))
            {
                string filename = node.Attribute("filename").Value;
                int result = ExecuteSQL(filename, conn);
                if (result != 0)
                {
                    throw new Exception(String.Format("Result of running script {0} was not 0.", filename));
                }
                count++;
            }

            //foreach (string script in list) {
            //    int result = ExecuteSQL(script, conn);
            //    if (result != 0)
            //    {
            //        throw new Exception(String.Format("Result of running script {0} was not 0.", script));
            //    }
            //}

            return count;
        }

        private static int ExecuteSQL(string filename, SqlConnection conn)
        {
            filename = Path.Combine("SQLScripts", filename);
            var content = File.ReadAllText(filename);

            using (SqlCommand cmd = new SqlCommand(content, conn)) {
                return cmd.ExecuteNonQuery();
            }
        }

        public static void RunRevisions(System.Data.Common.DbConnection dbConnection)
        {
            throw new NotImplementedException();
        }
    }
}
